package cn.fl.mcr.controller;


import cmm.mid.core.framework.page.ListPageVO;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.exception.BaseException;

import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.mcr.export.McrMonitorCheckExportBean;
import cn.fl.mcr.service.IMcrMonitorCheckService;
import cn.fl.mcr.vo.McrMonitorCheckVO;
import cn.lb.framework.poi.excel.ExcelExportUtil;
import cn.lb.framework.poi.excel.entity.ExportParams;
import cn.lb.framework.poi.excel.entity.enmus.ExcelType;
import cn.lb.framework.poi.excel.export.styler.ExcelExportStylerDefaultImpl;
import cn.lionbridgecapital.loan.model.base.Pager;
import cn.lionbridgecapital.loan.model.condition.McrMonitorCheckQC;
import cn.lionbridgecapital.loan.model.dto.McrMonitorCheckDDTO;
import cn.lionbridgecapital.loan.model.utils.DateUtils;
import cn.lionbridgecapital.loan.model.utils.StringUtils;
import cn.lionbridgecapital.loan.utils.BaseLogUtils;
import com.alibaba.fastjson.JSONObject;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Description: 卓远对账表 控制层
 */
@Controller
@RequestMapping("/mcr/mcrMonitorCheck")
public class McrMonitorCheckController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(McrMonitorCheckController.class);

	/**
	 * McrMonitorCheck 服务层BEAN
	 */
	@Autowired
	private IMcrMonitorCheckService mcrMonitorCheckService;
	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		Long startTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "toListPage", "加载列表页面.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());
		
		ModelAndView view = new ModelAndView("mcr/mcrMonitorCheck/mcrMonitorCheckList");
		
		Long endTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "toListPage", "加载列表页面.耗时：" + (endTm-startTm), CurrentThreadContext.getCurrentUserName());
		return view;
	}


	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET, RequestMethod.POST})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		Long startTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "initList", "加载列表页面.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());

		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String crtTmStart = request.getParameter("crtTmStart");
		String crtTmEnd = request.getParameter("crtTmEnd");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		McrMonitorCheckQC qc = new McrMonitorCheckQC();
		if (StringUtils.isNotEmpty(crtTmStart)) {
			qc.setCrtTmStart(DateUtils.formatStringToDate(crtTmStart,DateUtils.YYYY_MM_DD));
		}
		if (StringUtils.isNotEmpty(crtTmEnd)) {
			qc.setCrtTmEnd(DateUtils.formatStringToDate(crtTmEnd,DateUtils.YYYY_MM_DD));
		}
		page.setCondition(qc);
		//TODO SOMETHING
		Pager pager = this.mcrMonitorCheckService.searchListPage(page);
		List<McrMonitorCheckVO> list = (List<McrMonitorCheckVO>) pager.getResultList();
		ListPageVO<McrMonitorCheckVO> listPage = new ListPageVO<McrMonitorCheckVO>(list, pager.getTotalCount());
		Long endTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "initList", "加载列表页面.耗时：" + (endTm-startTm), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}


	/**
	 * 对账导出
	 */
	@RequestMapping(value = "/exportFile.do", method = {RequestMethod.GET, RequestMethod.POST})
	public void outExcel(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger,"billCheckExport","对账导出.操作人:"+CurrentThreadContext.getCurrentUserId());

		String checkId = request.getParameter("id");
		BaseLogUtils.info(logger, "billCheckExport", "对账导出.参数：checkId=" + checkId );

		try {
			List<McrMonitorCheckDDTO> mcrMonitorCheckDDTOS = mcrMonitorCheckService.selectDtlById(Long.valueOf(checkId));
			if (Objects.isNull(mcrMonitorCheckDDTOS)) {
				throw new BaseException("请求数据不存在!");
			}
			List<McrMonitorCheckExportBean> mcrMonitorCheckExportBeans = new ArrayList<>();
			for (McrMonitorCheckDDTO mcrMonitorCheckDDTO : mcrMonitorCheckDDTOS) {
				McrMonitorCheckExportBean mcrMonitorCheckExportBean =new McrMonitorCheckExportBean();
				mcrMonitorCheckExportBean.setBillId(mcrMonitorCheckDDTO.getBillId());
				mcrMonitorCheckExportBean.setCrCntNo(mcrMonitorCheckDDTO.getCrCntNo());
				mcrMonitorCheckExportBean.setDownCrCntNo(mcrMonitorCheckDDTO.getDownCrCntNo());
				mcrMonitorCheckExportBean.setDownGuaranteeAmt(mcrMonitorCheckDDTO.getDownGuaranteeAmt());
				mcrMonitorCheckExportBean.setDownGuaranteeState(mcrMonitorCheckDDTO.getDownGuaranteeState());
				mcrMonitorCheckExportBean.setDownPaydtlId(mcrMonitorCheckDDTO.getDownPaydtlId());
				mcrMonitorCheckExportBean.setUpCrCntNo(mcrMonitorCheckDDTO.getUpCrCntNo());
				mcrMonitorCheckExportBean.setUpGuaranteeAmt(mcrMonitorCheckDDTO.getUpGuaranteeAmt());
				mcrMonitorCheckExportBean.setUpGuaranteeState(mcrMonitorCheckDDTO.getUpGuaranteeState());
				mcrMonitorCheckExportBean.setUpPaydtlId(mcrMonitorCheckDDTO.getUpPaydtlId());
				mcrMonitorCheckExportBean.setRemark(mcrMonitorCheckDDTO.getRemark());
				mcrMonitorCheckExportBeans.add(mcrMonitorCheckExportBean);
			}
			BaseLogUtils.info(logger, "billCheckExport", "查询文件数据："+ JSONObject.toJSONString(mcrMonitorCheckDDTOS));
			export("卓远对账明细", McrMonitorCheckExportBean.class, mcrMonitorCheckExportBeans, response);
			return;
		} catch (BaseException e) {
			BaseLogUtils.error(logger, "billCheckExport", "对账导出.ERROR：" + e.getMessage(), CurrentThreadContext.getCurrentUserName());
		} catch (Exception e) {
			BaseLogUtils.error(logger, "billCheckExport", "对账导出,系统错误..ERROR:" + e.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
	}
	/**
	 * 数据导出
	 * @param fileName
	 * @param classz
	 * @param data
	 * @param response
	 */
	private void export(String fileName, Class classz, List data, HttpServletResponse response) {
		String excelTitle = fileName;
		String sheetName = fileName;
		ExportParams params = new ExportParams(excelTitle, sheetName, ExcelType.HSSF);
		//HSSF是POI工程对Excel 97(-2007)文件操作的纯Java实现;
		//XSSF是POI工程对Excel 2007 OOXML (.xlsx)文件操作的纯Java实现
		//SXSSF基于XSSF的低内存占用的API
		params.setColor(HSSFColor.BRIGHT_GREEN.index);//表头颜色
		params.setStyle(ExcelExportStylerDefaultImpl.class);//ExcelExportStylerBorderImpl 有边框样式 ExcelExportStylerColorImpl  有边框间隔行样式 ExcelExportStylerDefaultImpl	默认的样式
		Workbook workbook = ExcelExportUtil.exportExcel(params, classz, data);
		OutputStream ouputStream = null;
		try {
			fileName=new String(fileName.getBytes("UTF-8"),"ISO8859-1");
			response.reset();
			response.setCharacterEncoding("utf-8");
			response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xls");// 设定输出文件头
			response.setContentType("application/x-msdownload");// 定义输出类型
			ouputStream = response.getOutputStream();
			workbook.write(ouputStream);
			ouputStream.flush();
			ouputStream.close();
		} catch (UnsupportedEncodingException e) {
			BaseLogUtils.error(logger, "-", "异常", e);
		} catch (IOException e) {
			BaseLogUtils.error(logger, "-", "异常", e);
		}finally {
			//关闭流
			if(ouputStream!=null){
				try {
					ouputStream.close();
				} catch (IOException e) {
					BaseLogUtils.error(logger, "-", "异常", e);
				}
			}
		}
	}

}

